/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hva.web.mvcwebapp.doa;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import nl.hva.web.mvcwebapp.controllers.UserController;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.models.User;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Thijs, Julien
 */
public class UserDAO {

    private static User user;

    public UserDAO() {
    }

    public static List<User> getAllUSers() {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        List<User> user_list = session.createCriteria(User.class).list();
        tx.commit();
        session.close();
        return user_list;
    }

    public static List<User> getAllTeachers() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        List<User> teacherlist = session.createCriteria(User.class).list();
        for (int i = 0; i < teacherlist.size(); i++) {
            User teacherData = (User) teacherlist.get(i);
            if (teacherData.getUserType() == 2) {
            }
        }
        tx.commit();
        session.close();
        return teacherlist;
    }
    
    public static List<Course> getUserCourses(int id){
//        int userid = (Integer) UserController.session_user.getAttribute("user_id"); // "id" aanpassen naar wat je het genoemd hebt.
        
        AnnotationConfiguration config = new AnnotationConfiguration();// FROM HERE ----------
        config.addAnnotatedClass(Course.class);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("from user_course WHERE id='" + id + "'");
        List<Course> usercourseslist = queryResult.list(); // TO HERE IS A SUCCESFUL SELECT STATEMENT -----------
        for (int i = 0; i < usercourseslist.size(); i++) {
            System.out.println(usercourseslist.get(i) + "gggggggggggggggggggggggggggggggg");
        }
        tx.commit();
        return usercourseslist;
    }

    public static User getUser(int user_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        User user = (User) session.get(User.class, user_id);
        tx.commit();
        return user;
    }

    public static ArrayList insertUser(User user) {
        ArrayList validation_errors = new ArrayList();

        return validation_errors;
    }

    public static ArrayList updateUser(int user_id) {
        ArrayList validation_errors = new ArrayList();

        return validation_errors;
    }

    public static void deleteUser(int user_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        User tempGebruiker = (User) session.load(User.class, user_id);
        session.delete(tempGebruiker);
        tx.commit();
        return;
    }

    public static User checkLogin(HttpServletRequest request) throws NoSuchAlgorithmException {

        String username = request.getParameter("username");
       // System.out.println(username);
        String password = request.getParameter("password");

        MessageDigest msgDigest = null;
        String hashValue = null;
        try {
            msgDigest = MessageDigest.getInstance("SHA1");
            msgDigest.update(password.getBytes("UTF-8"));
            byte rawByte[] = msgDigest.digest();
            hashValue = (new BASE64Encoder()).encode(rawByte);

        } catch (NoSuchAlgorithmException e) {
            System.out.println("No Such Algorithm Exists");
        } catch (UnsupportedEncodingException e) {
            System.out.println("The Encoding Is Not Supported");
        }
        
      

        AnnotationConfiguration config = new AnnotationConfiguration();// FROM HERE ----------
        config.addAnnotatedClass(User.class);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        session.beginTransaction();
        Query queryResult = session.createQuery("from User WHERE username='" + username + "'");
        List usernameCheck = queryResult.list(); // TO HERE IS A SUCCESFUL SELECT STATEMENT -----------
        for (int i = 0; i < usernameCheck.size(); i++) {
            User userData = (User) usernameCheck.get(i);
            System.out.println(userData.getPassword());
            if (hashValue.equals(userData.getPassword())) {
                System.out.println("password verified!"); // THIS IS A SUCCESFUL LOGIN
                System.out.println("Query Succesful!"); // SUCCESFUL QUERY DOESN'T MEAN SUCCESFUL LOGIN
                tx.commit();
                user = userData;
                return user;
            } else {
                System.out.println("Someone tried to login with username " + username + " and password: " + password + "");
                userData = null;
                return null;
            }
            
        }
        return null;
        
    }

    public static int checkRegisterUnique(HttpServletRequest request) {
        int unique;
        String username = request.getParameter("username");
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(User.class);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("from User WHERE username='" + username + "'");
        List uniqueName = queryResult.list();
        if (uniqueName.isEmpty()) {
            unique = 1;
        } else {
            unique = 0;
        }
        tx.commit();
        return unique;
    }

    public static String[] checkValidation(HttpServletRequest request) {
        String onlyLetters = "[a-zA-Z]";
        String emailFormat = (".+@.+\\.[a-z]+");
        String[] validationError = new String[10];
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String email = request.getParameter("email");
        String landOfOrigin = request.getParameter("landOfOrigin");
        String profilepicture = request.getParameter("profilepicture");
        if (username.isEmpty()) {
            validationError[0] = "Username is not filled in! Please provide a username.";
            System.out.println("test6");
        } else if (username.length() < 5) {
            validationError[1] = "Username is too short! Your username should contain at least 5 characters.";
        } else if (username.length() > 15) {
            validationError[2] = "Username is too long! Your username should have a maximum length of 15 characters.";
        }
        if (password.isEmpty()) {
            validationError[3] = "Password is not filled in! Please provide a password.";
        } else if (password.length() < 6) {
            validationError[4] = "Password too short! This instabilizes the security of your account.";
        }
        if (password2.equals(password) != true) {
            validationError[5] = "Passwords don't match! Please make sure you fill in your password correctly twice.";
        }
        if (firstname.isEmpty()) {
            validationError[6] = "First name is not filled in! Please provide your first name.";
//        } else if (firstname.) {
//            validationError.add("First name can only contain letters!");
        }
        if (lastname.isEmpty()) {
            validationError[7] = "Last name is not filled in! Please provide your last name.";
//        } else if (lastname.matches(onlyLetters)) {
//            validationError.add("Last name can only contain letters!");
        }
        if (email.isEmpty()) {
            validationError[8] = "E-mail is not filled in! Please provide your e-mail.";
        } else if (email.matches(emailFormat) == false) {
            validationError[9] = "E-mail should be the following format: Person@Example.Text";
        }
        if (landOfOrigin.isEmpty()) {
            validationError[10] = "Nationality is not filled in!";
        }
        if (checkRegisterUnique(request) != 1) {
            validationError[11] = "Username not available!";
        }
        for (int i = 0; i < validationError.length; i++) {
            System.out.println(validationError[i]);
        }
        System.out.println("Validation succesful!");
        return validationError;
    }
}
